package com.lyrcsoft;

/**
 * @author fujc-dev@qq.com
 * @date 2023/8/1 11:07
 */

import java.io.*;

public class PipedOutputStreamExample {

    public static void main(String[] args) {
        // 创建一对PipedInputStream和PipedOutputStream
        PipedInputStream input = new PipedInputStream();
        PipedOutputStream output = new PipedOutputStream();

        try {
            // 将输入流和输出流连接起来
            input.connect(output);

            // 创建一个写线程
            Thread writerThread = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        // 写入一些数据到PipedOutputStream
                        output.write("Hello, World!".getBytes("UTF-8"));
                        // 刷新PipedOutputStream
                        output.flush();
                        // 关闭PipedOutputStream
                        output.close();
                    } catch (IOException e) {
                        System.out.println("Error writing to pipe: " + e.getMessage());
                    }
                }
            });

            // 创建一个读线程
            Thread readerThread = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        // 读取PipedInputStream中的数据
                        byte[] buffer = new byte[1024];
                        int len = input.read(buffer);
                        // 将读取的字节转换为字符串，并输出到控制台
                        String content = new String(buffer, 0, len, "UTF-8");
                        System.out.println(content);
                        // 关闭PipedInputStream
                        input.close();
                    } catch (IOException e) {
                        System.out.println("Error reading from pipe: " + e.getMessage());
                    }
                }
            });

            // 启动写线程和读线程
            writerThread.start();
            readerThread.start();

            // 等待写线程和读线程完成
            writerThread.join();
            readerThread.join();
        } catch (IOException | InterruptedException e) {
            System.out.println("Error communicating between threads: " + e.getMessage());
        }
    }
}
